﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MyOA.Model;
using MyOA.BLL;

namespace MyOA.UI.Message.MessageManage
{
    public partial class SendMessage : System.Web.UI.Page
    {
        MessageToUserManager messageToUserManager = new MessageToUserManager();
        BranchInfoManager branchInfoManager = new BranchInfoManager();
        DepartInfoManager departInfoManager = new DepartInfoManager();
        UserInfoManager userInfoManager = new UserInfoManager();
        MessageManager messageManager = new MessageManager();
        UserInfo userInfo = null;
        string word = string.Empty;        //初始化提示语
        int ifDraft = 0;                  //标示是否为草稿纸
        int messageId = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["loginId"] == null)
            {
                Response.Redirect("~/Login.aspx");
            }
            else
            {
                ifDraft = Convert.ToInt32(Request.QueryString["IfDarft"]);
                messageId = Convert.ToInt32(Request.QueryString["messageId"]);
                string loginId = Session["loginId"].ToString();
                userInfo = userInfoManager.GetUserInfoByLoginId(loginId); //获取用户信息
                //首次加载绑定数据信息
                if (!IsPostBack)
                {
                    loadInfo();
                    if (Request.QueryString["messageId"] != null)
                    {
                        MyOA.Model.Message message = messageManager.getMessageByMessageId(messageId);
                        txtTitle.Text = message.MsgTitle;
                        txtContent.Text = message.MsgContent;
                        loadReceiveUser(messageId); //加载收信人
                    }
                    lblCreateTime.Text = Convert.ToString(DateTime.Now);
                    lblCreateUser.Text = userInfo.UserName;
                }
            }
        }
        //转发信息时加载收信人信息
        private void loadReceiveUser(int messageId)
        {
            //根据messageId查找所有收信人
            IList<UserInfo> userList = userInfoManager.getAllUserInfoByMessageId(messageId);
            foreach (UserInfo user in userList)
            {
                //如果登录者非收信人
                if (user.UserId != userInfo.UserId)
                {
                    ListItem item = new ListItem();
                    item.Value = user.UserId.ToString();
                    item.Text = user.Depart.Branch.BranchShortName + "—" + user.Depart.DepartName + "—" + user.UserName;
                    lbReceiveUsers.Items.Add(item);
                }
            }
        }

        //选定发送信息人员操作
        protected void tvUsers_SelectedNodeChanged(object sender, EventArgs e)
        {
            //当节点深度小于2时，侧提示选择非用户
            if (tvUsers.SelectedNode.Depth < 2)
            {
                word = "您选择了非用户名，请查证！";
            }
            //选择为用户名
            else
            {
                UserInfo CheckuserInfo = userInfoManager.GetUserInfoByUserId(Convert.ToInt32(tvUsers.SelectedNode.Value));
                //判断登录用户与选择用户是否为同一用户
                if (CheckuserInfo.UserId == userInfo.UserId)
                {
                    word = "对不起，您不能将自己作为收件人！";
                    string script = string.Format("<script>Alert('{0}',null,null,'温馨提示','href()')</script>", word);
                    ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "", script, false);
                }
                else
                {
                    //实例化一个数据项用于绑定用户信息
                    ListItem item = new ListItem();
                    item.Value = CheckuserInfo.UserId.ToString();
                    item.Text = CheckuserInfo.Depart.Branch.BranchShortName + "-" + CheckuserInfo.Depart.DepartName + "-" + CheckuserInfo.UserName;
                    //判断选择用户是否已选择
                    if (lbReceiveUsers.Items.Contains(item))
                    {
                        word = "对不起，该用户已经存在！";
                        string script = string.Format("<script>Alert('{0}',null,null,'温馨提示','href()')</script>", word);
                        ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "", script, false);
                    }
                    else
                    {
                        lbReceiveUsers.Items.Add(item);
                    }
                }
            }
        }
        //添加到草稿纸
        protected void btnDraftMessage_Click(object sender, EventArgs e)
        {
            //如果ifDraft为1，则为草稿纸中的信息，修改其中信息
            if (ifDraft == 1)
            {
                //根据MessageId获取草稿信息
                MyOA.Model.Message message = messageManager.getMessageByMessageId(messageId);
                message.RecordTime = DateTime.Now;
                message.MsgContent = txtContent.Text;
                message.MsgTitle = txtTitle.Text;
                message.IfPublish = 0;
                //删除原收信人地址
                messageToUserManager.deleteMessageToUserByMessageId(messageId);
                //添加新收信人
                addMessageToUser(messageId);
                int result = messageManager.updateMessageByMessageId(message);
                if (result > 0)
                {
                    word = "草稿修改成功";
                }
                else
                {
                    word = "草稿修改失败";
                }
            }
            //如果ifDraft不为1，则不为草稿纸中的信息，添加草稿纸
            else
            {
                int num = addMesssage(0);
                if (num > 0)
                {
                    int result = addMessageToUser(num);
                    if (result > 0)
                    {
                        word = "草稿纸添加成功！";
                    }
                    else
                    {
                        word = "草稿纸添加失败！";
                    }
                }
                else
                {
                    word = "草稿纸添加失败！";
                }
            }
            string script = string.Format("<script>Alert('{0}',null,null,'温馨提示','href()')</script>", word);
            ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "", script, false);
        }
        //取消按钮事件
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("ManageMessage.aspx");
        }
        //删除已添加的发送用户信息事件
        protected void btnDelReceiveUser_Click(object sender, EventArgs e)
        {
            //如果为选择用户
            if (lbReceiveUsers.SelectedItem == null)
            {
                word = "请选择要删除的用户";
            }
            else
            {
                //遍历删除选择的用户
                IList<ListItem> list = new List<ListItem>();
                foreach (ListItem item in lbReceiveUsers.Items)
                {
                    if (item.Selected)
                    {
                        list.Add(item);
                    }
                }
                foreach (ListItem item in list)
                {

                    lbReceiveUsers.Items.Remove(item);
                }
                word = "成功删除用户";
            }
            string script = string.Format("<script>Alert('{0}',null,null,'温馨提示','')</script>", word);
            ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "", script, false);

        }
        //发送消息事件
        protected void btnSendMessage_Click(object sender, EventArgs e)
        {
            //如果ifDraft为1，则为草稿纸中的信息，修改其ifPublish
            if (ifDraft == 1)
            {
                //根据MessageId获取草稿信息
                MyOA.Model.Message message = messageManager.getMessageByMessageId(messageId);
                //根据MessageId获取收信人信息
                //MyOA.Model.MessageToUser messageToUser = messageToUserManager.GetMessageToUserByMessageId(messageId);
                //重新给Message赋值
                message.IfPublish = 1;
                message.RecordTime = DateTime.Now;
                message.MsgContent = txtContent.Text;
                message.MsgTitle = txtTitle.Text;
                //删除原收信人地址
                messageToUserManager.deleteMessageToUserByMessageId(messageId);
                //添加新收信人
                addMessageToUser(messageId);
                //修改Message信息
                int result = messageManager.updateMessageByMessageId(message);
                if (result > 0)
                {
                    word = "信息发送成功";
                }
                else
                {
                    word = "信息发送失败";
                }
            }
            //如果ifDraft为0，则为新发送的信息，执行添加
            else
            {
                int num = addMesssage(1);
                if (num > 0)
                {
                    int result = addMessageToUser(num);
                    if (result > 0)
                    {
                        word = "信息发送成功！";
                    }
                    else
                    {
                        word = "信息发送失败！";
                    }
                }
                else
                {
                    word = "信息发送失败！";
                }
            }
            string script = string.Format("<script>Alert('{0}',null,null,'温馨提示','href()')</script>", word);
            ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "", script, false);
        }
        //向Message表中添加信息，返回新添加的MessageId
        private int addMesssage(int ifPublish)
        {
            MyOA.Model.Message message = new MyOA.Model.Message();
            message.IfPublish = ifPublish;
            message.RecordTime = DateTime.Now;
            message.MsgTitle = txtTitle.Text;
            message.MsgContent = txtContent.Text;
            message.FromUser = userInfo;
            int result = messageManager.insertMessage(message);
            return result;
        }
        //根据新添加的MessageId向MessageToUser表中添加信息
        private int addMessageToUser(int messageId)
        {
            int result = 0;
            foreach (ListItem item in lbReceiveUsers.Items)
            {
                MessageToUser messageToUser = new MessageToUser();
                messageToUser.IfRead = 0;
                messageToUser.IfRecycle = 0;
                messageToUser.Message = messageManager.getMessageByMessageId(messageId);
                messageToUser.ToUser = userInfoManager.GetUserInfoByUserId(Convert.ToInt32(item.Value));
                result = messageToUserManager.insertMessageToUser(messageToUser);
            }
            return result;
        }
        //根据MessageId修改MessageToUser信息
        //private int updateMessageByMessageId(int messageId)
        //{
        //    int result = 0;
        //    IList<MessageToUser> messageToUserList=messageToUserManager.getAllMessageToUserByMessageId(messageId);
        //    foreach(MessageToUser messageToUser in messageToUserList)
        //    {
        //        messageToUser.ToUser=
        //    }
        //}
        //绑定Treeview
        private void loadInfo()
        {
            IList<BranchInfo> branchInfoList = branchInfoManager.GetAllBranchInfo();
            tvUsers.Nodes.Clear();
            foreach (BranchInfo branchInfo in branchInfoList)
            {
                int branchId = branchInfo.BranchId;
                string branchName = branchInfo.BranchName;
                TreeNode branchNode = CreateTreeNode(branchName, branchId, "~/images/menuclose.gif", "");
                CreateDepartNode(branchId, branchNode);
                tvUsers.Nodes.Add(branchNode);
            }
        }
        /// <summary>
        /// 创建节点
        /// </summary>
        /// <param name="text">节点显示的文本</param>
        /// <param name="value">节点值</param>
        /// <param name="img">节点旁显示的图像的URL</param>
        /// <param name="url">单击节点时链接到的URL</param>
        private TreeNode CreateTreeNode(string text, int value, string img, string url)
        {
            TreeNode treeNode = new TreeNode();
            treeNode.Text = text;
            treeNode.Value = Convert.ToString(value);
            treeNode.ImageUrl = img;
            treeNode.NavigateUrl = url;
            return treeNode;
        }
        /// <summary>
        /// 创建部门节点信息
        /// </summary>
        /// <param name="branchId">父节点Id</param>
        /// <param name="branchNode">父节点对象</param>
        private void CreateDepartNode(int branchId, TreeNode branchNode)
        {
            IList<DepartInfo> departInfoList = departInfoManager.getAllDepartInfoByBranchId(branchId);
            foreach (DepartInfo departInfo in departInfoList)
            {
                int departId = departInfo.DepartId;
                string departName = departInfo.DepartName;
                TreeNode departNode = CreateTreeNode(departName, departId, "", "~/images/CloseTree.gif");
                CreateUserNode(departId, departNode);
                addNode(branchNode, departNode);
            }
        }
        /// <summary>
        /// 创建用户节点信息
        /// </summary>
        /// <param name="departId"></param>
        /// <param name="departNode"></param>
        private void CreateUserNode(int departId, TreeNode departNode)
        {
            IList<UserInfo> userInfoList = userInfoManager.getAllUserInfoByDepartId(departId);
            foreach (UserInfo userInfo in userInfoList)
            {
                int userId = userInfo.UserId;
                string userName = userInfo.UserName;
                TreeNode userNode = CreateTreeNode(userName, userId, "~/Images/person.gif", "");
                addNode(departNode, userNode);
            }
        }
        /// <summary>
        /// 把子节点加载到父节点
        /// </summary>
        /// <param name="FatherNode">父节点对象</param>
        /// <param name="ChildNode">子节点对象</param>
        private void addNode(TreeNode FatherNode, TreeNode ChildNode)
        {
            FatherNode.ChildNodes.Add(ChildNode);
        }
    }
}
